#!/usr/bin/python
# -*- coding: UTF-8 -*-

import sys
import os
import shutil
import getopt

global cwd
cwd = os.getcwd()
global abs_path
abs_path = os.path.abspath(os.path.dirname(__file__)) 
if cwd != abs_path:
    os.chdir(abs_path)

def install(url):
    result = os.path.split(url)
    if len(result) == 0:
        return False
    package_name = result[len(result)-1]
    if os.path.exists(os.path.join('package', package_name)):
        return False
    os.chdir("package")
    if os.system("git clone " + url) != 0:
        print("install " + package_name + " failed")
        return False
    print("install " + package_name + " success")
    return True

def update(package_name):
    if not os.path.exists(os.path.join('package', package_name, '.git')):
        print("There no git repo.")
        return True
    if not os.path.exists(os.path.join('package', package_name)):
        print("update " + package_name + " failed")
        return False    
    os.chdir(os.path.join('package', package_name))
    if os.system("git pull") != 0:
        print("update " + package_name + " failed")
        return False
    print("update " + package_name + " success")
    return True

def remove(package_name):
    if not os.path.exists(os.path.join('package', package_name)):
        print("remove " + package_name + " failed")
        return False    
    shutil.rmtree(os.path.join('package', package_name))
    print("remove " + package_name + " success")
    return True

def usage():
    print("")
    print("    -h,--help                 help doc.")
    print("    -i,--install git repo.    install package from remote git repo.")
    print("    -u,--update package name  update package from remote git repo.")
    print("    -r,--remove package name  delete package")

if __name__ == "__main__":
    opts = None
    args = None
    try:
        opts,args = getopt.getopt(sys.argv[1:],'-i:-u:-r:',["install=", "update=", "remove="])
        if len(opts) == 0:
            usage()
        else:
            for opt, value in opts:
                if opt in ("-i", "--install"):
                    install(value)
                elif opt in ("-u", "--update"):
                    update(value)
                elif  opt in ("-r", "--remove"):
                    remove(value)
                else:
                    usage()
    except getopt.GetoptError as e:
        print(str(e))
